﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZG_member.BLL;
using System.Configuration;
namespace ZG_member
{
    public partial class IntegrationExchangeForm : Form
    {
        MainForm mainForm;
        public VisualCardPrinter_NPPrinter_New.VisualCardPrinter_NPPrinter vnp;
        int ret;
        string id = "0";
        public IntegrationExchangeForm(MainForm main, string ids, VisualCardPrinter_NPPrinter_New.VisualCardPrinter_NPPrinter VNp) 
        {
            InitializeComponent();
            mainForm = main;
            vnp = VNp;
            id = ids;
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"]; 
        }

        private void IntegrationExchangeForm_Load(object sender, EventArgs e)
        {
             this.Opacity = 0;
            this.timer1.Start();
            
            gifts gif = new gifts();
            DataTable dt = gif.GetList("").Tables[0];
            DgvGifts.DataSource = dt;
            read();
            
        }

        private void DgvGifts_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            bool isNull = false;
            for (int i = 0; i < DgvGifts1.RowCount; i++)
            {
                if (DgvGifts.CurrentRow.Cells[0].Value.ToString() == DgvGifts1.Rows[i].Cells[0].Value.ToString())
                {
                    isNull = true;
                    break;
                }
            }
            if (isNull == true)
            {
                MessageBox.Show("此礼品已添加");
            }
            else
            {
                addRows();
            }
        }

        private void addRows()
        {
            DataGridViewRow dgvRow = new DataGridViewRow();
            DataGridViewTextBoxCell dgvCell0 = new DataGridViewTextBoxCell();
            DataGridViewTextBoxCell dgvCell1 = new DataGridViewTextBoxCell();
            DataGridViewTextBoxCell dgvCell3 = new DataGridViewTextBoxCell();
            dgvCell0.Value = DgvGifts.CurrentRow.Cells[0].Value;
            dgvCell1.Value = DgvGifts.CurrentRow.Cells[1].Value;
            dgvCell3.Value = 1;
            dgvRow.Cells.Add(dgvCell0);
            dgvRow.Cells.Add(dgvCell1);
            dgvRow.Cells.Add(dgvCell3);
            DgvGifts1.Rows.Add(dgvRow);
        }
        ZG_member.SendMsgsForm sf = new ZG_member.SendMsgsForm();
        private void btnSure_Click(object sender, EventArgs e)
        {
            MemberSaleForm m = new MemberSaleForm(mainForm,id, this.TxtCardId.Text, vnp);
            memberInfo member = new memberInfo();
            Model.memberInfo memberMod = new Model.memberInfo();
            memberMod = member.GetModels(this.TxtCardId.Text);
            if (memberMod.status==2)
            {
                MessageBox.Show("您的卡片已停用！");
                return;
            }
            if (this.TxtCardId.Text == "")
            {
                MessageBox.Show("请先输入会员卡号");
                return;
            }
            
            giftExchangeNotes gifEx = new giftExchangeNotes();
            Model.giftExchangeNotes gifExMod = new Model.giftExchangeNotes();
            gifts gif = new gifts();
            Model.gifts gifMod = new Model.gifts();
            bool isNull = true;
            int num = 0;
            for (int i = 0; i < DgvGifts1.Rows.Count; i++)
            {
                try
                {
                    int j = int.Parse(DgvGifts1.Rows[i].Cells[2].Value.ToString());
                }
                catch
                {
                    MessageBox.Show("兑换个数请输入数字");
                    return;
                }
                gifMod = gif.GetModel(int.Parse(DgvGifts1.Rows[i].Cells[0].Value.ToString()));
                int amount = int.Parse(DgvGifts1.Rows[i].Cells[2].Value.ToString());
                num += amount * gifMod.Integral.Value;
                if (gifMod.giftamount < amount)
                {
                    isNull = false;
                    break;
                }
            }
            if (DgvGifts1.Rows.Count == 0)
            {
                MessageBox.Show("兑换个数请输入数字");
                return;
            }
            if (num >= int.Parse(this.Txtpoint.Text)) 
            {
                MessageBox.Show("积分不足无法兑换");
                return;
            }
            if (isNull == false)
            {
                MessageBox.Show("礼品不足无法兑换");
                return;
            }

            memberInfo memberInfo = new memberInfo();
            Model.memberInfo memberInfoMod = new Model.memberInfo();
            memberInfoMod = memberInfo.GetModels(this.TxtCardId.Text);      
            memberInfoMod.point = memberInfoMod.point - num;
            memberInfo.Update(memberInfoMod);
            this.Txtpoint.Text = memberInfoMod.point.ToString();

            for (int i = 0; i < DgvGifts1.Rows.Count; i++) 
            {
                gifMod = gif.GetModel(int.Parse(DgvGifts1.Rows[i].Cells[0].Value.ToString()));
                int amount = int.Parse(DgvGifts1.Rows[i].Cells[2].Value.ToString());
                gifMod.giftamount = gifMod.giftamount - amount;
                gif.Update(gifMod);

                gifMod = gif.GetModel(int.Parse(DgvGifts1.Rows[i].Cells[0].Value.ToString()));
                int amount1 = int.Parse(DgvGifts1.Rows[i].Cells[2].Value.ToString());
                gifExMod.giftId = int.Parse(DgvGifts1.Rows[i].Cells["Column6"].Value.ToString());
                gifExMod.date = DateTime.Now;
                gifExMod.integral = amount1 * gifMod.Integral.Value;
                gifExMod.giftName = DgvGifts1.Rows[i].Cells[1].Value.ToString();
                gifExMod.memberId = this.TxtCardId.Text;
                gifExMod.giftAmount = int.Parse(DgvGifts1.Rows[i].Cells[2].Value.ToString());
                int aaa = gifEx.Add(gifExMod);
                //if (aaa>0)
                //{
                //    BLL.Duanxingneirong blldx = new Duanxingneirong();
                //    Model.Duanxingneirong dxmodle = blldx.getmodel(4);
                //    string fakaneirong = string.Format(dxmodle.Fasongneirong, num, memberInfoMod.point - num);
                //    fakaneirong += "";
                //    try
                //    {
                //        if (faxing == "1")
                //        {
                //            sf.sendMsg(fakaneirong, memberInfoMod.Tel);
                //        }

                //    }
                //    catch (Exception)
                //    {
                //        MessageBox.Show("由于计算机未连网，不能发信息！");

                //    }
                   
                //} 
            }
            string status = vnp.RfidCardRequestAndReadData("1", "FFFFFFFFFFFF");
            if (status == "0" || status == "1")
            {
                
            }
            else
            {
                MemberSaleForm mb = new MemberSaleForm(mainForm,memberInfoMod.memberCardId, this.TxtCardId.Text, vnp);
                Model.memberInfo mode = mb.GetModel();
                int Nowday = DateTime.Now.Day;
                int Nowyue = DateTime.Now.Month;

                int shengriday = ((DateTime)mode.birthDay).Day;
                int shengriyue = ((DateTime)mode.birthDay).Month;
                consumeSolution ct = new consumeSolution();
                Model.consumeSolution css = ct.GetModel((int)mode.cardType);
                string sex = (bool)mode.sex ? "男" : "女";
                //i.keyongjifen(mode.memberId, (int)mode.cardType);
                int keyong = (int)mode.point - int.Parse(keyongjifen(mode.memberId, (int)mode.cardType));
                string[] ModelArray = new string[] { mode.memberId, css.solutionName, mode.memberName, sex, "正常", mode.createDate.ToString(), mode.expiresDate.ToString(), mode.point.ToString(), num.ToString(), keyong.ToString(),"0", mode.Balance.Value.ToString("F1"), "0","无","无" };
                string Go = mb.print(ModelArray);
                birthdayremind br = new birthdayremind();
                Model.birthdayremind brmodl = br.GetModel(2);
                int aa = br.tixingday(this.TxtCardId.Text);
                if (aa < brmodl.Remindday && aa != 0)
                {
                    if (Nowyue == shengriyue)
                    {
                        if (Nowday < shengriday)
                        {
                            string one = brmodl.Remindcontent.Replace("{now}", DateTime.Now.ToString("yyyy-MM-dd") + "\n");
                            string two = one.Replace("{leftDays}", aa.ToString());
                            Go += two + "\n";
                        }
                    }
                    if (Nowyue < shengriyue)
                    {
                        string one = brmodl.Remindcontent.Replace("{now}", DateTime.Now.ToString("yyyy-MM-dd") + "\n");
                        string two = one.Replace("{leftDays}", aa.ToString());
                        Go += two + "\n";
                    }
                }
                else if (aa == 0)
                {
                    Go += brmodl.Nowremindcontent1 + "\n";
                }
                vnp.PrintBufferClear();
                vnp.PrintCharacterDataSetting(Go);
                vnp.ErasePrintDischarge3();
            }
            
            MessageBox.Show("换礼成功");
            this.Close();
        }
        string faxing = ConfigurationManager.AppSettings["faxin"];
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (DgvGifts1.Rows.Count > 0)
            {
                DgvGifts1.Rows.RemoveAt(DgvGifts1.CurrentRow.Index);
            }
        }

        private void DgvGifts1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //if (DgvGifts1.Rows.Count > 0)
            //{
            //    DgvGifts1.Rows.RemoveAt(DgvGifts1.CurrentRow.Index);
            //}
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //timer开启
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            //timer关闭
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }
        int flag = 0;
        private void IntegrationExchangeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

      
        private void button1_Click(object sender, EventArgs e)
        {
            string status = vnp.RfidCardRequestAndReadData("1", "FFFFFFFFFFFF");
            if (status == "1")
            {
                //MessageBox.Show("机器未插卡");
            }
            else
                if (status == "0")
                {
                    MessageBox.Show("端口未打卡");
                }
                else
                {
                    //string data = "";
                    //byte blocknum = 1;
                    //VN.WriteData(blocknum, data);
                    //return;
                    //VN.ReadData(blocknum, ref data);
                    this.TxtCardId.Text = status;
                    id = this.TxtCardId.Text;
                }

            memberInfo member = new memberInfo(); 
            Model.memberInfo memberMod = new Model.memberInfo();
            try
            {
                if (status == "1" || status == "0")
                {
                    if (this.TxtCardId.Text == "")
                    {
                        MessageBox.Show("对不起！请您插卡或者输入您的卡号！");
                        return;
                    }
                    memberMod = member.GetModelList("memberId='" + this.TxtCardId.Text + "'")[0];
                }
                else
                {
                    memberMod = member.GetModelList("memberCardId='" + this.TxtCardId.Text + "'")[0];
                }

            }
            catch
            {

                MessageBox.Show("找不到该会员");
                return;
            }
            if (memberMod.status == 2)
            {
                this.TxtCardId.Text = "";
                MessageBox.Show("对不起，你的卡已停用！");

                return;
            }
            this.Txtpoint.Text = memberMod.memberId;
            this.Txtpoint.Text = memberMod.point.ToString();
            this.Txtname.Text = memberMod.memberName;
        }
        public void read() {
            //int status = VN.StatusDemand();
            //if (status != 0x02)
            //{

            //}
            //else
            //{
            //    string data = "";
            //    byte blocknum = 1;
            //    //VN.WriteData(blocknum, data);
            //    //return;
            //    VN.ReadData(blocknum, ref data);
            //    this.TxtCardId.Text = data;
            //}

            memberInfo member = new memberInfo();
            Model.memberInfo memberMod = new Model.memberInfo();
            try
            {
                //if (status != 0x02)
                //{
                    memberMod = member.GetModels(id);
                //}
                //else
                //{
                //    memberMod = member.GetModelList("memberCardId='" + this.TxtCardId.Text + "'")[0];
                //}
            }
            catch
            {

                MessageBox.Show("找不到该会员");
                return;
            }
            if (memberMod.status == 2)
            {
                this.TxtCardId.Text = "";
                MessageBox.Show("对不起，你的卡已停用！");

                return;
            }
            
            int jifen = (int)memberMod.point- int.Parse(keyongjifen(memberMod.memberId.ToString(), (int)memberMod.cardType));
            this.TxtCardId.Text = memberMod.memberId;
            this.Txtpoint.Text = jifen.ToString();
            this.Txtname.Text = memberMod.memberName;
        }
        private void TxtCardId_Leave(object sender, EventArgs e)
        {
            if (this.Txtname.Text == "")
            {
                read();
            }
            else
            {

            }
            
        
        }

        public string keyongjifen(string memberId,int cardtype) {
            wasteBook wb = new wasteBook();
            Model.wasteBook wbmod = new Model.wasteBook();
            try
            {
                wbmod = wb.GetModelList("membercardId = '" + memberId + "'")[0];
            }
            catch (Exception)
            {
                
                return "0";
            }
           
            
            consumeSolution cs = new consumeSolution();
            Model.consumeSolution csmod = cs.GetModel(cardtype);
            string keyong = wb.keyongjifen(wbmod.memberCardId, csmod.Integralday);
            return keyong;
        }

        private void TxtCardId_TextChanged(object sender, EventArgs e)
        {
            this.Txtname.Text = "";
            this.Txtpoint.Text = "";
            if (TxtCardId.Text == "")
            {
                return;
            }
            memberInfo member = new memberInfo();
            Model.memberInfo memberMod = new Model.memberInfo();
            try
            {
                //if (status != 0x02)
                //{
                memberMod = member.GetModels(this.TxtCardId.Text);
                //}
                //else
                //{
                //    memberMod = member.GetModelList("memberCardId='" + this.TxtCardId.Text + "'")[0];
                //}
            }
            catch
            {

                
                return;
            }
            if (memberMod == null)
            {
                return;
            }
            if (memberMod.status == 2)
            {
                this.TxtCardId.Text = "";
                MessageBox.Show("对不起，你的卡已停用！");

                return;
            }

            int jifen = (int)memberMod.point - int.Parse(keyongjifen(memberMod.memberId.ToString(), (int)memberMod.cardType));
            this.TxtCardId.Text = memberMod.memberId;
            this.Txtpoint.Text = jifen.ToString();
            this.Txtname.Text = memberMod.memberName;
        }

        private void TxtCardId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }
    }
}
